<script>
import * as IncreaseUtil from "@/components/util/IncreaseUtil";
export default {
  data() {
    return {
      selectedSubject: {
        label: '请选择用能主体'
      },
      selectedEnergyId: null,
      selectedItemId: null,
      selectedItemOneId: null,
      selectedTimeRange: [new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 7), new Date()],
      treeData: [],
      energyInfo: {
        view: [],
        data: []
      },
      itemInfo: {
        view: [],
        data: []
      },
      itemOneInfo: {
        view: [],
        data: []
      },
      dialogVisible: false,
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      pieChartOption: {
        tooltip: {
          trigger: 'item',
          formatter: function (c) {
            let unite = c.seriesName
            return '项目：' + c.data.name + '<br>能耗：' + c.data.value + ' ' + unite + '<br>占比：' + c.percent + '%';
          }
        },
        series: [
          {
            type: 'pie',
            data: []
          }
        ]
      },
      lineChartOption: {
        grid: {
          left: '2%',
          right: '2%',
          bottom: '2%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (c) {
            return '时间：' + c[0].name + '<br>能耗：' + c[0].value + ' ' + c[0].seriesName;
          }
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          },
        },
        series: [
          {
            name: 'kgce',
            type: 'line',
            data: []
          }
        ]
      }
    };
  },
  mounted() {
    this.fetchTreeData()
    this.fetchBaseList()
    this.fetchData()
  },
  methods: {
    queryData: function () {
      this.fetchData()
    },
    fetchTreeData: function () {
      const data = {content: {excludeTypes:["METER","POINT","GATEWAY"]}}
      this.$axios({url:'/ems/client/energy/search/subject/tree',data: data}).then((content) => {
        this.treeData = content.list
      });
    },
    fetchPieChartData: function () {
      let fromDate = null
      let toDate = null
      if (this.selectedTimeRange.length === 2) {
        const s = this.$getTimeInfo(this.selectedTimeRange[0]);
        const e = this.$getTimeInfo(this.selectedTimeRange[1])
        fromDate = s.year + '-' + s.month + '-' + s.day + ' 00:00:00';
        toDate = e.year + '-' + e.month + '-' + e.day + ' 23:59:59';
      }
      const data =
          {
            content: {
              subjectId:this.selectedSubject.id,
              subjectType: this.selectedSubject.type,
              energyId: this.selectedEnergyId,
              itemId: this.selectedItemId,
              itemOneId: this.selectedItemOneId,
              fromDate: fromDate,
              toDate: toDate,
              dateType: 'day'
            }
          }
      let showTypeKey = 'increaseStandValue'
      if (this.selectedEnergyId) {
        this.pieChartOption.series[0].name = IncreaseUtil.getJsonArrValueByField(this.energyInfo.data, 'id', this.selectedEnergyId, 'cumulateUnit')
      }
      this.$axios({url: '/ems/client/index/item/compare', data: data}).then((content) => {
        const list = content.list
        this.pieChartOption.series[0].data = []
        for (let i = 0; i < list.length; i ++) {
          const item = list[i]
          this.pieChartOption.series[0].data.push({name: item.name, value: this.$doubleVal(item['' + showTypeKey + ''])});
        }
        this.$nextTick(() => {
          const chart = this.$echarts.init(this.$refs.pieChart)
          chart.setOption(this.pieChartOption)
        })
      })
    },
    fetchLineChartData: function () {
      let fromDate = null
      let toDate = null
      let showType = 'hour'
      if (this.selectedTimeRange.length === 2) {
        const s = this.$getTimeInfo(this.selectedTimeRange[0]);
        const e = this.$getTimeInfo(this.selectedTimeRange[1])
        const dis = this.selectedTimeRange[1].getTime() - this.selectedTimeRange[0].getTime()
        if (dis > 1000 * 60 * 60 * 24) {
          showType = 'day'
        }
        fromDate = s.year + '-' + s.month + '-' + s.day + ' 00:00:00';
        toDate = e.year + '-' + e.month + '-' + e.day + ' 23:59:59';
      }
      const data =
          {
            content: {
              subjectId:this.selectedSubject.id,
              subjectType: this.selectedSubject.type,
              energyId: this.selectedEnergyId,
              itemId: this.selectedItemId,
              itemOneId: this.selectedItemOneId,
              fromDate: fromDate,
              toDate: toDate,
              toDateType: showType
            }
          }
      this.$axios({url:'/ems/client/index/energy/time/trend',data: data}).then((content) => {
        const list = content.list
        this.lineChartOption.xAxis.data = [];
        this.lineChartOption.series[0].data = [];
        for (let i = 0; i < list.length; i ++) {
          const item = list[i]
          this.lineChartOption.xAxis.data.push(item.time);
          if (this.selectedEnergyId) {
            this.lineChartOption.series[0].name = IncreaseUtil.getJsonArrValueByField(this.energyInfo.data, 'id', this.selectedEnergyId, 'cumulateUnit')
            this.lineChartOption.series[0].data.push(this.$doubleVal(item['increaseRealValue']));
          }else {
            this.lineChartOption.series[0].data.push(this.$doubleVal(item['increaseStandValue']));
          }
        }
        this.$nextTick(() => {
          this.chart = this.$echarts.init(this.$refs.lineChart)
          this.chart.setOption(this.lineChartOption)
        })
      });
    },
    handleClose() {
      this.dialogVisible = false
    },
    fetchBaseList: function () {
      const data = {content: {}}
      this.$axios({url:'/ems/client/base/energy/list',data: data}).then((content) => {
        const list = content.list;
        list.forEach(function (item) {
          if (item.nameInfo) {
            item.nameInfo = JSON.parse(item.nameInfo)
          }
        })
        this.energyInfo.data = list
        this.energyInfo.view = list
      });
      this.$axios({url:'/ems/client/base/item/list',data: data}).then((content) => {
        this.itemInfo.data = content.list
      })
      this.$axios({url:'/ems/client/base/item/one/list',data: data}).then((content) => {
        this.itemOneInfo.data = content.list
      })
    },
    fetchData: function () {
      this.fetchLineChartData()
      this.fetchPieChartData()
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    treeClick: function (item) {
      this.dialogVisible = false
      this.selectedSubject = item
    },
    selectChange: function (type, id) {
      const getNextList = function (linkId, linkField, arr) {
        const rs = []
        arr.forEach(item => {
          const linkVal = item['' + linkField + '']
          if (linkVal === linkId) {
            rs.push(item)
          }
        })
        return rs;
      }
      if (type === 'itemOne') {
        return
      }
      this.selectedItemOneId = null
      if (type === 'item') {
        this.itemOneInfo.view = getNextList(id, 'itemId', this.itemOneInfo.data)
        return
      }
      this.selectedItemId = null
      if (type === 'energy') {
        this.itemInfo.view = getNextList(id, 'energyId', this.itemInfo.data)
      }
    },
  }
};
</script>

<template>
<div>
  <el-row>
    <el-col :span="24" style="height: 50px;">
      <el-button type="text" @click="dialogVisible = true" style="margin-left: 1%;background-color: white;width: 350px;color: rgb(192, 196, 204);">{{selectedSubject.label}}</el-button>
      <el-dialog
          title="提示"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose">
          <el-tree
              class="filter-tree"
              :data="treeData"
              :props="defaultProps"
              :filter-node-method="filterNode"
              @node-click="treeClick"
              ref="tree">
          </el-tree>
      </el-dialog>
      &nbsp;
      能源分类：<el-select v-model="selectedEnergyId" placeholder="请选择能源类型" @change="selectChange('energy', selectedEnergyId)">
      <el-option
          v-for="item in energyInfo.view"
          :key="item.id"
          :label="item.nameInfo['zh-CN']"
          :value="item.id">
      </el-option>
    </el-select>
      &nbsp;
      分项：<el-select v-model="selectedItemId" placeholder="请选择分项" @change="selectChange('item', selectedItemId)">
        <el-option
            v-for="item in itemInfo.view"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      &nbsp;
      一分项：<el-select v-model="selectedItemOneId" placeholder="请选择一分项">
      <el-option
          v-for="item in itemOneInfo.view"
          :key="item.id"
          :label="item.name"
          :value="item.id">
      </el-option>
    </el-select>
      &nbsp;
      <el-date-picker
          v-model="selectedTimeRange"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
      </el-date-picker>
      &nbsp;
      <el-button @click="queryData">查询</el-button>
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="18">
      <div ref="lineChart" style="height: 500px;"></div>
    </el-col>
    <el-col :span="6">
      <div ref="pieChart" style="height: 500px;"></div>
    </el-col>
  </el-row>
</div>
</template>

<style>

</style>
